//
//  NSString+Additions.m
//  DJAppModule
//
//  Created by Lynn_Lin on 2018/3/22.
//

#import "NSString+Additions.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (Additions)
+ (CGFloat)heightForText:(NSString *)text constWidth:(CGFloat)width attributes:(NSDictionary *)attributes {
    CGSize size;
    if ([self validStringByTrimming:text]) {
        size = [self sizeForString:text constWith:width attribtes:attributes];
        return (size.height);
    }
    return 0.0;
}

+ (BOOL)validStringByTrimming:(NSString *)string {
    if ([string isKindOfClass:[NSString class]]) {
        string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        return (string && string.length > 0);
    }
    return NO;
}

+ (CGSize)sizeForString:(NSString *)string constWith:(CGFloat)width attribtes:(NSDictionary *)dictionary {
    if (!string || string.length < 1 || width == 0) {
        return CGSizeZero;
    }
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:dictionary context:nil];
    return rect.size;
}

+ (CGFloat)singleLineHeight:(NSDictionary *)dictionary
{
    // 当文字内出现换行符\r\n时，计算单行会出现问题
    return ceilf([self sizeForString:@"计算单行高度" constWith:MAXFLOAT attribtes:dictionary].height);
}

- (CGSize)suitableSizeWithFont:(CGFloat)fontSize
{
    NSDictionary *attributeDic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    CGSize suitableSize = [self sizeWithAttributes:attributeDic];
    return suitableSize;
}

- (NSString *)findValueFromUrlStr:(NSString *)keyStr
{
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",keyStr];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:self
                                      options:0
                                        range:NSMakeRange(0, [self length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [self substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        return tagValue;
    }
    return @"";
}

- (BOOL)isValidMobile
{
    NSString *phoneRegex = @"1[*0-9]{10}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

- (NSString *)MaskPhoneNumber
{
    if (self.length == 11)
    {
        return [self stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    else
    {
        return self;
    }
}

- (NSString *)MD5String {
    const char *cstr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cstr, (uint32_t)strlen(cstr), result);
    
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
    
}

- (NSString*)urlEncoding
{
    NSString* result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                             kCFAllocatorDefault,
                                                                                             (CFStringRef)self,
                                                                                             NULL, // characters to leave unescaped
                                                                                             (CFStringRef)@":!*();@/&?#[]+$,='%’\"",
                                                                                             kCFStringEncodingUTF8));
    return result;
}
- (NSString *)urlEncodeString
{
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                             (CFStringRef)self,
                                                                                             NULL,
                                                                                             (CFStringRef)@";/?:@&=$+{}<>,",
                                                                                             kCFStringEncodingUTF8));
    return result;
}

- (NSString *)dj_urlDecoderString {
    if (!self || ![self isKindOfClass:[NSString class]] ||self.length == 0) return nil;
    
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)self, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

- (NSString *)stringMD5Encode
{
    if ([self length] == 0) {
        return nil;
    }
    const char *cStr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    NSString *string = [NSString stringWithFormat:
                        @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                        result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
                        result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]
                        ];
    return string;
}

// 根据出入字符串、限制宽度、字体大小计算字体宽度
+ (CGSize)getStringSize:(NSString *)strString strWidth:(CGFloat)width fontSize:(UIFont *)font{
    
    //    CGSize labsize = [strString sizeWithFont:font constrainedToSize:CGSizeMake(width, 2000) lineBreakMode:NSLineBreakByWordWrapping];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    //    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    CGSize labsize = [strString
                      boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                      options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                      attributes:attributes
                      context:nil].size;
    
    return labsize;
}

// 判断是否输入了表情符号
+ (BOOL)isContainsEmoji:(NSString *)string {
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3 || ls == 0xfe0f) {
                 isEomji = YES;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 isEomji = YES;
             }
         }
         // modify by lidi for ios7 九宫格键盘
         if (0x278b <= hs && hs <= 0x2792) {
             isEomji = NO;
         }
     }];
    return isEomji;
}

- (NSString *)dj_deleteEmoji {
    if (!self || ![self isKindOfClass:[NSString class]] ||self.length == 0) return nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:self
                                                               options:0
                                                                 range:NSMakeRange(0, [self length])
                                                          withTemplate:@""];
    return modifiedString;
}

- (NSString *)dj_detectUrlComponentsWithKey:(NSString *)strKey{
    NSArray *urls = [self componentsSeparatedByString:@"#"];
    if (urls.count) {
        NSString *valueStr;
        for (NSString *url in urls) {
            NSArray *urlComponents = [url componentsSeparatedByString:@"?"];
            for (NSString *queryItemsStr in urlComponents) {
                //由&进行拆分
                NSArray *querys = [queryItemsStr componentsSeparatedByString:@"&"];
                for (NSString *queryStr in querys) {
                    NSArray *keyValues = [queryStr componentsSeparatedByString:@"="];
                    if (keyValues.count==2) {
                        NSString *key = [keyValues firstObject];
                        if ([key isEqualToString:strKey]) {
                            valueStr =[keyValues lastObject];
                            break;
                        }
                    }
                }
                if (valueStr) {
                    break;
                }
            }
            if (valueStr) {
                break;
            }
        }
        if (valueStr.length) {
            return valueStr;
        }
    }
    return nil;
}
@end
